import requests
import re
import datetime

# content_list存放所有弹幕
content_list = []
# 爬取开始日期和结束日期范围内的弹幕
begin = datetime.date(2023, 12, 28)
end = datetime.date(2023, 12, 28)
for i in range((end - begin).days + 1):
    day = begin + datetime.timedelta(days=i)
    url = f'https://www.bilibili.com/video/BV1Ec411z7j2/?spm_id_from=333.880.my_history.page.click&vd_source=8c01d38d167f99f327ea28b3caf35b12{day}'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'cookie': 'buvid3=18D0CE38-460E-7712-2CF8-21258C796A5103549infoc; b_nut=1662542605; buvid4=D4558573-B6BA-445D-80E6-BF387EA6F03103549-022090717-kji2bknSwKfJePD52JZ2mYcQOxtNmzZ4FgqXGzin5vUe5IVn9thEtA%3D%3D; buvid_fp=8db2862df677cee57482815a37c196b2; _uuid=9102F1B53-3CDB-AD3D-FC5D-75D6810C211E266662infoc; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTQxMjkwNDMsImlhdCI6MTcxMzg2OTc4MywicGx0IjotMX0.IscN0SJ5SceCB0zKotlIzJUiqMD_vKZp6wF0V6NcM3Q; bili_ticket_expires=1714128983; rpdid=|(JYlm|luJJk0Ju~uJ)Ym)l|; bili_jct=a9d136833ed50451d513e7598a799f12; DedeUserID=1444596502; DedeUserID__ckMd5=041f0f7cb70c00c0; b_lsid=105894DC10_18F0F1077B7; bsource=search_baidu; enable_web_push=DISABLE; FEED_LIVE_VERSION=V8; header_theme_version=CLOSE; home_feed_column=5; browser_resolution=1707-799; bmg_af_switch=1; bmg_src_def_domain=i0.hdslb.com; bp_video_offset_1444596502=923516482323742725; CURRENT_FNVAL=4048; sid=h8166ug7'
    }
    response = requests.get(url=url, headers=headers)
    response.encoding = 'utf-8'

    temp_list = re.findall('[\u4e00-\u9fa5]+', response.text)
    content_list.extend(temp_list)
    print("爬取", day, "日弹幕,获取到：", len(temp_list), "条弹幕，已经增加到总列表。总列表共有", len(content_list),
          "条弹幕。")
print(content_list)
# 保存数据
content = '\n'.join(content_list)
with open('弹幕.txt', mode='a', encoding='utf-8') as f:
    f.write(content)
print("保存完成")

